package com.data;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;

import com.bean.JobBean;
import com.constant.Constant;
import com.net.ClientError;
import com.net.ClientException;
import com.net.RequestParameter;

/**
 * 专场招聘会，比校园招聘更多信息
 * 请求参数为page，page=1表示第一次请求，page = 2 表示下一次请求，该参数必传
 * 
 * @author mjh
 *
 */
public final class MoreJobData extends BaseData
{
	private final static String TAG = "more_job_data";
	
	private final static String MORE_JOB_URL = "http://xhjy.xhu.edu.cn/more_zc.asp";//?应该是：http://jy.xhu.edu.cn/more_zc.asp
	
	/**
	 * 用户保存当前连接地址，用户在webview中查看该详情
	 */
	private String currentUrl = null;
	
	/**
	 * 就业信息列表
	 */
	private ArrayList<JobBean> mJobList;
	/**
	 * 总共多少条数据
	 */
	private int mTotal;
	
	@Override
	public void startParse(RequestParameter parameter) throws Exception, ClientException
	{
		Log.i(TAG, "开始获取更多就业信息");
		
		String page = parameter.getValue("page");
		if(page == null)
			throw new Exception("请求参数传递错误！");
		
		String url = null;
		String refer = null;
		
		if(page.equals("1"))
		{
			Log.i(TAG, "第一次请求该页面");
			url = MORE_JOB_URL;
			refer = "http://xhjy.xhu.edu.cn/";//?http://jy.xhu.edu.cn
		}
		else if(page.equals("2"))
		{
			Log.i(TAG, "请求下一页面数据");
			url = MORE_JOB_URL + "?page=" + parameter.getValue("page");
			refer = MORE_JOB_URL;
		}
		else
		{
			Log.i(TAG, "请求第三页以上数据");
			url =  MORE_JOB_URL + "?page=" + parameter.getValue("page");
			refer = MORE_JOB_URL + "?page=" + (Integer.parseInt(parameter.getValue("page")) - 1);
		}
		
		currentUrl = url;
		
//		System.out.println(currentUrl);
		
		String stream = openConnection(url, refer);
		if(stream == null)
			return;
		
		readStream(stream);
	}
	/**
	 * 返回连接请求数据
	 * @return 连接失败返回null
	 */
	public String openConnection(final String urlS, final String referer) throws Exception
	{
		URL url = new URL(urlS);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Host", "xhjy.xhu.edu.cn");
		connection.setRequestProperty("Referer", referer);
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		connection.setDoOutput(true);
		connection.setUseCaches(false);

		connection.connect();
		
		if(connection.getResponseCode() != 200)
		{
			Log.i(TAG, "网络请求数据失败, 错误代码：" + connection.getResponseCode());
			throw new ClientException("网络连接失败", ClientError.ERROR_CONNECTION);
		}
		
		return getWebSource(connection.getInputStream(), "gb2312");
		
	} // openConnection
	
	
	/**
	 * 公司招聘信息数据格式如下：
	 * <table width="800" border="0" cellspacing="0" cellpadding="0" align="center">
	 * 		<tr height="24">标题信息</tr>
	 * 
	 *      <tr height="20">
	 *      	<td width="350" bgcolor="#F0E8F0">
	 *      		 <a href="news_zc.asp?id=7220" style="font-size:12px;color:#000000;font-weight:normal " target=_blank>沁园集团股份有限公司</a>
	 *          </td>
	 *          <td width="150" bgcolor="#F0E8F0"><div align="center" >2012-11-15</div></td>
	 *          <td width="150" bgcolor="#F0E8F0"><div align="center" >14:30</div></td>
	 *          <td width="150" bgcolor="#F0E8F0"><div align="center" >2B404</div></td>
	 *      </tr>
	 *      <tr>
	 *      	<td height="1" colspan = 4 bgcolor="#5AAEFF"></td>
	 *      </tr>
	 *      
	 *      <tr height="20">
	 *      	<td width="350" bgcolor="#E8DBE8">
	 *          	<a href="news_zc.asp?id=7059" style="font-size:12px;color:#000000;font-weight:normal " target=_blank>锦泰财产保险公司</a>
	 *          </td>
	 *          <td width="150" bgcolor="#E8DBE8"><div align="center" >2012-11-14</div></td>
	 *          <td width="150" bgcolor="#E8DBE8"><div align="center" >14:30</div></td>
	 *          <td width="150" bgcolor="#E8DBE8"><div align="center" >2B404</div></td>
	 *      </tr>
	 *      <tr>
	 *      	<td height="1" colspan = 4 bgcolor="#5AAEFF"></td>
	 *      </tr>
	 *      ...
	 *  </table>
	 * 
	 * @param stream
	 */
	private void readStream(final String stream) throws Exception
	{
		Document document = Jsoup.parse(stream);
		
		Elements table = document.select("table");
		if(table == null)
		{
			Log.e(TAG, "搜索table节点为null");
			throw new Exception("table节点不存在");
		}
		
//		System.out.println(table.size());
//		System.out.println(table.get(5).html().toString());
		
		// 解析搜索结果总数
		analyzeTotal(table.get(5));
		
		
		Element temp = table.get(4);
		if(temp == null)
		{
			Log.e(TAG, "查找目标table节点为null");
			throw new Exception("数据table节点不存在");
		}
		
		table = temp.select("tr");
		if(table == null)
		{
			Log.e(TAG, "tr标签为null");
			throw new Exception("没有找到解析数据标签");
		}
		
		mJobList = new ArrayList<JobBean>();
		
		// i跳过头结点信息和中间线条标签
		for(int i = 1, length = table.size(); i < length; i += 2)
		{
			JobBean bean = new JobBean();
			Element td = table.get(i);
			bean.title = td.child(0).child(0).ownText();
			bean.url = "http://xhjy.xhu.edu.cn/" + td.child(0).child(0).attr("href");
			bean.referer = currentUrl;
			bean.date = td.child(1).child(0).ownText();
			bean.time = td.child(2).child(0).ownText();
			bean.site = td.child(3).child(0).ownText();
			
			mJobList.add(bean);
		}
		
//		// 解析返回结果数量
//		Elements form = document.select("form");
//		System.out.println("size:" + form.size());
//		for(int i = 0; i < form.size(); i++)
//		{
//			System.out.println(form.get(i).html().toString());
//			Log.e("tag", "error");
//		}
	} // readStream
	
	/**
	 * 解析返回记录的条数，源码中的格式有误，数据格式如下：
	 * <table width="800" border="0" align="center" cellpadding="0" cellspacing="0"> 
	 *  <tbody>
	 *    <tr>
	 *    	<td>&nbsp;</td>
	 *    </tr>
	 *    <tr bgcolor="#FFFFFF">
	 *    	 <form method="Post" action="more_zc.asp"></form>
	 *   	 <td height="30" align="center">
	 *    		<a href="more_zc.asp?page=1" style="font-size:12px;color:#000000;font-weight:normal">首页</a> &nbsp;
	 *    		<a href="more_zc.asp?page=2" style="font-size:12px;color:#000000;font-weight:normal">上一页</a> &nbsp;
	 *    		<a href="more_zc.asp?page=4" style="font-size:12px;color:#000000;font-weight:normal">下一页</a> 
	 *    		<a href="more_zc.asp?page=6" style="font-size:12px;color:#000000;font-weight:normal">尾页</a>&nbsp;页次：
	 *    		<strong><font color="red">3</font>/6</strong>页 &nbsp;共
	 *    		<b><font color="#FF0000">147</font></b>
	 *    		条记录
	 *    		<b>25</b>条记录/页 转到：
	 *    		<input type="text" name="page" size="4" maxlength="10" class="input" value="3" />
	 *    		<input class="input" type="submit" value=" Goto " name="cndok" />
	 *    		<p></p>
	 *    	</td>
	 *     </tr>
	 *   </tbody>
	 * </table>
	 * @param table
	 */
	public void analyzeTotal(Element table) throws Exception
	{
//		System.out.println(table.html().toString());
		Element form = table.child(0);
		if(form == null)
		{
			Log.i(TAG, "tbody标签为null");
			throw new IOException("解析返回总数时tbody标签为空");
		}
		
		form = form.child(1);
		if(form == null)
		{
			Log.i(TAG, "数据节点tr标签null");
			throw new IOException("解析返回总数时tr标签为空");
		}
		
		Element td = form.child(1);
		if(td == null)
		{
			Log.i(TAG, "解析数据时td标签null");
			throw new IOException("解析返回总数是td标签为空");
		}
		
		Elements b = td.select("b");
		mTotal = Integer.parseInt(b.get(0).child(0).ownText());
		
		Log.i(TAG, "解析返回结果总数成功");
		
	} // analyzeTotal
	
	public int getTotal()
	{
		return this.mTotal;
	}
	
	public ArrayList<JobBean> getJobList()
	{
		return this.mJobList;
	}
	
	
	public void printData()
	{
		System.out.println("返回结果数：" + mTotal);
		for(int i = 0; i < mJobList.size(); i++)
		{
			JobBean bean = mJobList.get(i);
			System.out.println(bean.title);
			System.out.println(bean.url);
			System.out.println(bean.referer);
			System.out.println(bean.date);
			System.out.println(bean.time);
			System.out.println(bean.site);
		}
	}

}
